<template>
    <div>
        <a-modal
         v-model:visible="visibleShow" 
         :title="formState.title == '新增' && formState.id?'编辑':formState.title" 
         @cancel="visibleShow = false"
         :width="formState.id && formState.fwjlx?'100%':600"
         :footer="null"
         :wrapClassName="formState.id && formState.fwjlx?'qualitySystem-full-modal':''"
         >
            <div class="quality-system-content" v-if="visibleShow">
                <div style="display: flex;">
                    <div :style="{width: formState.id && formState.fwjlx?'40%':'100%'}">
                        <a-form :form="form" layout="inline" class="quality-system-form">
                            <a-form-item label="文件名称" class="flex-1-input-box">
                                <a-input
                                v-if="!formState.disabled"
                                v-model:value="formState.fwjmc"
                                placeholder="请输入文件名称"
                                v-decorator="[
                                    'fwjmc', { initialValue:formState.fwjmc, rules: rules.fwjmc}
                                ]"/>
                                <span v-else>{{ formState.fwjmc }}</span>
                            </a-form-item>
                            <a-form-item label="分类" class="flex-1-input-box">
                                <a-tree-select
                                    v-if="!formState.disabled"
                                    v-model:value="formState.ftypeid"
                                    :expandedKeys="expandedKeys" 
                                    :tree-data="treeTypeList" 
                                    :replaceFields='replaceFields'
                                    style="width:200px"
                                    placeholder="请选择分类"
                                    tree-default-expand-all
                                />
                                <span v-else>{{ formState.ftype }}</span>
                            </a-form-item>
                            <a-form-item v-if="!formState.disabled" label="文件编号" class="flex-1-input-box">
                                <a-input
                                v-if="!formState.disabled"
                                placeholder="请输入文件编号"
                                v-model:value="formState.fwjbh"/>
                                <span v-else>{{ formState.fwjbh }}</span>
                            </a-form-item>
                            <a-form-item v-if="!formState.disabled" label="受控版本" class="flex-1-input-box">
                                <a-input
                                v-if="!formState.disabled"
                                placeholder="请输入受控版本"
                                v-model:value="formState.fskbb"/>
                                <span v-else>{{ formState.fskbb }}</span>
                            </a-form-item>
                            <a-form-item v-if="!formState.disabled" label="修改次数" class="flex-1-input-box">
                                <a-input
                                v-if="!formState.disabled"
                                style="width:200px"
                                placeholder="请输入修改次数"
                                v-model:value="formState.fxgcs"/>
                                <span v-else>{{ formState.fxgcs }}</span>
                            </a-form-item>
                            <a-form-item v-if="!formState.disabled" label="实施日期" class="flex-1-input-box">
                                <a-date-picker
                                v-if="!formState.disabled"
                                style="width:200px"
                                placeholder="请输入实施日期"
                                v-model:value="formState.fssrq"
                                />
                                <span v-else>{{ formState.fssrq }}</span>
                            </a-form-item>
                            <a-form-item label="上传日期" class="flex-1-input-box">
                                <a-date-picker
                                v-if="!formState.disabled"
                                style="width:200px"
                                placeholder="请输入上传日期"
                                v-model:value="formState.fscrq"
                                />
                                <span v-else>{{ formState.fscrq }}</span>
                            </a-form-item>
                            <!-- <a-form-item label="文件类型">
                                <a-input
                                v-if="!formState.disabled"
                                :disabled="true"
                                placeholder="文件类型"
                                v-model:value="formState.fwjlx"/>
                                <span v-else>{{ formState.fwjlx }}</span>
                            </a-form-item> -->
                            <!-- <a-form-item label="文件路径">
                                <a-input
                                v-if="!formState.disabled"
                                :disabled="true"
                                placeholder="文件路径"
                                v-model:value="formState.fwjlj"/>
                                <span v-else>{{ formState.fwjlj }}</span>
                            </a-form-item> -->
                            <a-form-item label="状态" class="flex-1-input-box">
                                <a-radio-group v-model="formState.fzt" v-if="!formState.disabled">
                                    <a-radio value="现行有效">
                                        现行有效
                                    </a-radio>
                                    <a-radio value="无效">
                                        无效
                                    </a-radio>
                                </a-radio-group>
                                <span v-else>{{ formState.fzt }}</span>
                            </a-form-item>
                            <!-- <a-form-item label="序号">
                                <a-input-number
                                v-if="!formState.disabled"
                                style="width:200px"
                                placeholder="请输入序号"
                                v-model:value="formState.forder"/>
                                <span v-else>{{ formState.forder }}</span>
                            </a-form-item> -->
                            <!-- <a-form-item label="文件" class="flex-1-input-box" v-if="formState.fwjlx">
                                <span class="file-box-v">
                                    <span style="line-height: 16px;">{{ formState.fwjmc.length>20?formState.fwjmc.substring(0,19)+'...':formState.fwjmc }}{{ formState.fwjlx }}</span>
                                    <a-icon type="download" style="font-size: 18px;color: #5ca3e5;margin-left: 10px;" @click="downloadClick"/>
                                    <a-icon type="eye" style="font-size: 18px;color: #1ab394;margin-left: 10px;" @click="viewClick"/>
                                </span>
                            </a-form-item> -->
                            <div style="width: 100%;display: flex;padding-left: 80px;" v-if="!formState.disabled">
                                <!-- 验证通过后才能打开选文件 -->
                                <div  v-if="formState.fwjmc">
                                    <a-upload  style="display: inline-block;" :beforeUpload="$event=>{return false}" action="" @change="saveBeforeUploading">
                                        <a-button class="blue-btn" type="default" icon="import">上传</a-button>
                                    </a-upload>
                                </div>
                                <a-button v-else class="blue-btn" type="default" icon="import" @click="saveBeforeUploading">上传</a-button>
                                <!-- <a-button v-if="formState.fwjlx" :loading="downloadFileLoading" style="margin: 0 15px;" class="blue-btn" type="primary" @click="downloadClick">下载</a-button>
                                <a-button v-if="formState.fwjlx" class="blue-btn" type="default" @click="viewClick">查看</a-button> -->
                            </div>
                            <!-- <div style="width: 100%;display: flex;justify-content: center;" v-if="formState.disabled&&formState.fwjlx">
                                <a-button class="blue-btn" type="default" @click="viewClick">查看</a-button>
                            </div> -->
                        </a-form>
                    </div> 
                    <div style="flex: 1;margin-left: 5px;" v-if="formState.id && formState.fwjlx">
                        <a-spin tip="正在加载中..." :spinning="spinning">
                            <div style="height: calc(100vh - 160px);">
                                <a-button v-if="!formState.views || (formState.views && formState.fsfyxxz !== 1)" :loading="downloadFileLoading" class="blue-btn" type="primary" @click="downloadClick">下载</a-button>
                                <iframe 
                                    v-if="iframeSrc && formState.id && formState.fwjlx"
                                    :key="iframeKey"
                                    :src="iframeSrc" 
                                    ref="iframeServerEditingRef" 
                                    scrolling="auto" 
                                    width="100%" 
                                    :height="(windowInnerHeight -170 )+'px'"
                                    style="border: 0;"
                                ></iframe>
                                <span v-else>当前文件发生错误，请下载文件浏览！</span>
                            </div>
                        </a-spin>
                    </div>
                </div>
                
                 <div v-if="!formState.disabled" style="
                    display: flex; justify-content: center;
                    margin-top: 20px; width: 100%;
                    background-color: #fff;">
                    <a-button @click="visibleShow = false">关闭</a-button>
                    <a-button style="margin: 0 20px;" class="blue-btn" type="primary" @click="handleOk(true)">保存</a-button>
                    <a-button class="blue-btn" type="primary" @click="handleOk(false)">保存并关闭</a-button>
                </div>
                <serverEditingView ref="serverEditingViewRef" @refreshChange="$event=>{}"/>
            </div>
        </a-modal>
    </div>
</template>
<script>
import moment from 'moment'
import { 
    uploadZltxwjFile, 
    addZltxwj, 
    queryById, 
    editZltxwj, 
    downloadFile, 
    spcyZltxwjHistoryGetZltxwjFile, 
    zltxwjClientOfficeApigetZltxwjFile, 
    zltxwjClientOfficeApigetLsZltxwjFile, 
} from './service/index'
import blobType from '@/common/blobType'
import serverEditingView from '@/components/comp-model-series/server-editing-view'
import YchConstant from '@/api/YchConstant'
import store from '@/store'
import { degrees, PDFDocument, rgb, StandardFonts } from 'pdf-lib'
export default {
    components:{
        serverEditingView
    },
    props:{

    },
    data(){
        return{
            formState:{},
            form: this.$form.createForm(this, { name: 'coordinated' }),
            treeTypeList:[],
            visibleShow:false,
            replaceFields: {
                children: 'children', //后端数组层级的名字
                key: 'id', //一般是id
                title: 'value',
                value: 'id' //onSelect(selectedKeys)的selectedKeys的参数值，便于获取然后返回给后端
            },
            expandedKeys:'',
            rules:{
                fwjmc: [{
                     required: true,
                     message: '请输入文件名称',
                     trigger: 'blur',
                 }],
            },
            fwjmc:'',
            downloadFileLoading:false,
            downloadFun:[zltxwjClientOfficeApigetZltxwjFile,zltxwjClientOfficeApigetLsZltxwjFile,],
            iframeSrc:'',
            iframeKey:null,
            windowInnerHeight:window.innerHeight,
            spinning:false,
        }
    },
    watch:{

    },
    mounted(){
        
    },
    methods:{
        getData(val,treeData){//无id先保存再修改
            this.formState = {}
            //console.log(val)
            this.treeTypeList = treeData
            this.fwjmc = val.fwjmc
            if(val.disabled){
                this.formState = {
                    ...val,
                    fssrq:val.fssrq?moment(val.fssrq).format('YYYY-MM-DD'):'',
                    fscrq:val.fscrq?moment(val.fscrq).format('YYYY-MM-DD'):'',
                }
            }else{
                this.formState = {
                    ...val,
                    fssrq:val.fssrq?moment(val.fssrq,'YYYY-MM-DD'):'',
                    fscrq:val.fscrq?moment(val.fscrq,'YYYY-MM-DD'):'',
                }
            }
            if(this.formState.id && this.formState.fwjlx){
                this.getIframe()
            }
        },
        getIframe(){
            // if(this.formState.historical){
            //     this.iframeSrc = bootConfig[process.env.NODE_ENV].locality_ApI + YchConstant.SPZX_SPCY + '/zltxwjClientOfficeApi/getLsZltxwjFile?id='+this.formState.id+'&aa='+Date.now()
            // }else{
            //     this.iframeSrc = bootConfig[process.env.NODE_ENV].locality_ApI + YchConstant.SPZX_SPCY + '/zltxwjClientOfficeApi/getZltxwjFile?id='+this.formState.id+'&aa='+Date.now()
            // }
            this.iframeSrc = ''
            this.spinning = true
            this.fetchAndAddWatermark()
            this.iframeKey = Date.now()
        },
        async fetchAndAddWatermark() {
            try {
                // 从接口获取PDF文件流
                if(!this.formState.id){
                    this.spinning = false
                    return
                }
                const data = await this.downloadFun[this.formState.funIndex]({id: this.formState.id})
                //console.log('我获取到了什么文件流？',data)
                const realnameDate = store.getters.userInfo.realname+moment().format('YYYY年MM月DD日')
                //console.log('水印文本',realnameDate)
                await this.previewPdfConstructor({
                    blob: data,
                    docTitle: 'window.open docTitle',
                    isAddWatermark: true, // 是否需要添加水印
                    watermark: { // watermark必填 里面可以不填
                        type: 'canvas',
                        text: realnameDate
                    }
                })
            } catch (error) {
                //console.log('Error fetching or adding watermark:', error);
            }
        },
        previewPdfConstructor({ blob, docTitle, isAddWatermark = false, watermark: { type = 'text', text = 'WFT', image } }){
            //console.log('1',blob)
            const _self = this
            if(!blob) {
                return console.error('[PDF Blob Is a required parameter]')
            }
            if(!isAddWatermark) { // 不添加水印
                 _self.preRightView(blob, docTitle)
            } else {
                let bytes,imageType
                if(type == 'image') {
                    if(!image) {
                    return console.error('["image" Is a required parameter]')
                    }
                    bytes = image.bytes
                    imageType = image.imageType
                }
                const map = {
                    // 'text': _self.addTextWatermark.bind(_self),
                    // 'image': _self.addImageWatermark.bind(_self),
                    'canvas': _self.addCanvasWatermark.bind(_self)
                }
                const pdfDoc =  PDFDocument.load(blob)
                let params
                if(type == 'text') params = { blob, pdfDoc, text, docTitle }
                if(type == 'image') params = { blob, pdfDoc, bytes, imageType, docTitle }
                if(type == 'canvas') params = { blob, pdfDoc, text, docTitle }
                this.resultUrl = map[type](params)
            }
        },
        async addCanvasWatermark({ blob, pdfDoc1, text, docTitle }) {
            //console.log('2',blob)
            // const pdfDoc =  await PDFDocument.load(blob)
            PDFDocument.load(blob).then(pdfDoc=>{
                // 旋转角度大小
                const rotateAngle = Math.PI / 4;
        
                // labels是要显示的水印文字，垂直排列
                let labels = new Array();
                labels.push(text);
            
                const pages = pdfDoc.getPages()
            
                const size = pages[0].getSize()
            
                let pageWidth = size.width
                let pageHeight = size.height

                //console.log('画布的宽高，',size.width,'-',size.height)
                let canvas = document.createElement('canvas');
                let canvasWidth = canvas.width = pageWidth;
                let canvasHeight = canvas.height = pageHeight;
            
                const context = canvas.getContext('2d');
                context.font = "15px Arial";
            
                // 先平移到画布中心
                context.translate(pageWidth / 2, pageHeight / 2 - 250);
                // 在绕画布逆方向旋转30度
                context.rotate(-rotateAngle);
                // 在还原画布的坐标中心
                context.translate(-pageWidth / 2, -pageHeight / 2);
            
                // 获取文本的最大长度
                let textWidth = Math.max(...labels.map(item => context.measureText(item).width));
            
                let lineHeight = 15, fontHeight = 12, positionY, i
                i = 0, positionY = 0
                while (positionY <= pageHeight) {
                positionY = positionY + lineHeight * 5
                i++
                }
                canvasWidth += Math.sin(rotateAngle) * (positionY + i * fontHeight) // 给canvas加上画布向左偏移的最大距离
                //console.log('给canvas加上画布向左偏移的最大距离',Math.sin(rotateAngle) * (positionY + i * fontHeight))
                canvasHeight = 2 * canvasHeight
                for (positionY = 0, i = 0; positionY <= canvasHeight; positionY = positionY + lineHeight * 5) {
                // 进行画布偏移是为了让画布旋转之后水印能够左对齐;
                context.translate(-(Math.sin(rotateAngle) * (positionY + i * fontHeight)), 0);
                for (let positionX = 0; positionX < canvasWidth; positionX += 1.5 * textWidth) {
                    let spacing = 0;
                    labels.forEach(item => {
                    context.fillText(item, positionX, positionY + spacing);        
                    context.fillStyle = 'rgba(0, 0, 0, .2)'; // 字体颜色
                    spacing = spacing + lineHeight;
                    })
                }
                context.translate(Math.sin(rotateAngle) * (positionY + i * fontHeight), 0);
                context.restore();
                i++
                }
                // 图片的base64编码路径
                let dataUrl = canvas.toDataURL('image/png');
                // 使用Xhr请求获取图片Blob
                let xhr = new XMLHttpRequest();
                xhr.open("get", dataUrl, true);
                xhr.responseType = "blob";
                xhr.onload = res => {
                const imgBlob = res.target.response
                // 获取Blob图片Buffer
                imgBlob.arrayBuffer().then(async buffer => {
                    const pngImage = await pdfDoc.embedPng(buffer)
                    for(let i = 0; i < pages.length; i++) {
                    pages[i].drawImage(pngImage)
                    }
                    // 序列化为字节
                    const pdfBytes = await pdfDoc.save()
                    this.preView(pdfBytes, docTitle)
                })
                }
                xhr.send();
            }).catch(error => {
                // 处理加载过程中的错误
                console.error('Error loading PDF:', error);
                this.spinning = false
            });
            
        },
        preView(stream, docTitle) {
            const blob = new Blob([stream], { type: 'application/pdf' });
            this.iframeSrc =  URL.createObjectURL(blob);
            this.spinning = false
        },
        getQueryById(id){
            queryById({id:id}).then(res=>{
                if(res.code == 200){
                    let val = res.result
                    this.formState = {
                        ...this.formState,
                        ...val,
                        fssrq:val.fssrq?moment(val.fssrq,'YYYY-MM-DD'):'',
                        fscrq:val.fscrq?moment(val.fscrq,'YYYY-MM-DD'):'',
                    }
                }else{
                    this.$message.warning(res.message)
                }
            })
        },
        viewClick(){
            this.$refs.serverEditingViewRef.getData({id:this.formState.id,type:'质量体系文件资源库',fwjlx:this.formState.fwjlx})
            this.$refs.serverEditingViewRef.serverEditingVisible = true
        },
        uploadFile({file}){
            //console.log('上传',file)
            if(typeof file.uid !== 'undefined') {
                const fileData = new FormData();
                fileData.append("file", file);
                fileData.append("id", this.formState.id);
                uploadZltxwjFile(fileData).then(res => {
                    //console.log(res)
                    if(res.code && res.code !== 200){
                        this.$message.warning('请上传pdf文件或者联系管理员!')
                    }else{
                        this.$message.success('上传成功')
                        this.getQueryById(this.formState.id)
                        this.$emit('successClick')
                    }
                })
            }else{
                this.$message.warning('请重新选择文件')
            }
        },
        downloadClick(){
            var that = this
            this.downloadFileLoading = true
            var fileName = this.formState.fwjmc+'.pdf'
            //console.log(fileName)
            let param = {id: this.formState.id,symc:store.getters.userInfo.realname+moment().format('YYYY年MM月DD日')}
            
            this.downloadFun[this.formState.funIndex](param).then((data) => {
                this.downloadFileLoading = false
                //console.log(data)
                if (data.code) {
                    that.$message.warning('文件下载失败')
                    return
                }
                let url = window.URL.createObjectURL(new Blob([data]), { type: blobType.type[blobType.suffix.indexOf('.pdf')] })
                let link = document.createElement('a')
                link.style.display = 'none'
                link.href = url
                link.setAttribute('download', fileName)
                document.body.appendChild(link)
                link.click()
                document.body.removeChild(link) //下载完成移除元素
                window.URL.revokeObjectURL(url) //释放掉blob对象
            })
        },
        saveBeforeUploading(file){
            //console.log(file)
            this.form.validateFields((err, values) => {
                if(!err){
                    let data = {
                        ...this.formState,
                        fssrq:this.formState.fssrq?moment(this.formState.fssrq).format('YYYY-MM-DD'):'',
                        fscrq:this.formState.fscrq?moment(this.formState.fscrq).format('YYYY-MM-DD'):'',
                    }
                    if(this.formState.id){
                        editZltxwj(data).then(res=>{
                            if(res.code == 200){
                                this.uploadFile(file)
                                this.$emit('successClick')
                                this.getIframe()
                            }else{
                                this.$message.warning(res.message)
                            }
                        })
                    }else{
                        addZltxwj(data).then(res=>{
                            if(res.code == 200){
                                this.formState.id = res.result
                                this.uploadFile(file)
                                this.$emit('successClick')
                                this.getIframe()
                            }else{
                                this.$message.warning(res.message)
                            }
                        })
                    }
                }
            })
        },
        handleOk(val){
            if(this.formState.disabled){
                this.visibleShow = false
            }else{
                this.form.validateFields((err, values) => {
                if(!err){
                    let data = {
                        ...this.formState,
                        fssrq:this.formState.fssrq?moment(this.formState.fssrq).format('YYYY-MM-DD'):'',
                        fscrq:this.formState.fscrq?moment(this.formState.fscrq).format('YYYY-MM-DD'):'',
                    }
                    if(this.formState.id){
                        editZltxwj(data).then(res=>{
                            if(res.code == 200){
                                this.$emit('successClick')
                                this.visibleShow = val
                                this.getQueryById(this.formState.id)
                            }else{
                                this.$message.warning(res.message)
                            }
                        })
                    }else{
                        addZltxwj(data).then(res=>{
                            if(res.code == 200){
                                this.formState.id = res.result
                                this.$emit('successClick')
                                this.visibleShow = val
                                this.getQueryById(this.formState.id)
                            }else{
                                this.$message.warning(res.message)
                            }
                        })
                    }
                }
            })
            }
        },
    }
}
</script>
<style lang="less">
.qualitySystem-full-modal{
    .ant-modal {
    max-width: 100%;
    top: 0;
    padding-bottom: 0;
    margin: 0;
  }
  .ant-modal-content {
    display: flex;
    flex-direction: column;
    height: calc(100vh);
  }
  .ant-modal-body {
    height: calc(100vh - 50px);
  }
}
.quality-system-form{
    .ant-form-item-label{
        width: 80px;
        background-color: #e6f7ff;
        margin-top: 4px;
        height: 32px;
        font-weight: 600;
        line-height: 32px;
        margin-right: 5px;
    }
    .ant-form-item-control-wrapper{
        width: 200px;
    }
    .ant-upload-list{
        display: none !important;
    }
    .file-box-v{
        display: inline-block;
        // flex-direction: column;
        // align-items: center;
        // justify-content: center;
        border: 1px solid #d9d9d9;
        // width: 104px;
        // height: 104px;
        padding: 0 10px;
        overflow: hidden;
        border-radius: 2px;
    
    }
    .file-icon-v{
        font-size: 42px;
        color: rgb(24, 144, 255);
    }
    .flex-1-input-box{
            display: flex;
            width: 100%;
            .ant-form-item-control-wrapper{
            flex: 1;
        }
        .ant-form-item-control{
            width: 100%;
        }
            .ant-input{
                width: 100% !important;
            }
        }
}
</style>